<?php
/**
 * Note: *
 * Date: 2020/3/26
 */
namespace App\Caches;

use App\Models\Role;
use Illuminate\Support\Facades\Cache;

class RoleCache
{
    const CACHE_TAG = 'role';

    /**
     * 处理后的 role 数据
     * @param $roleId
     * @return array
     */
    private static function handleData($roleId)
    {
        $role = Role::with('roleAccess')->find($roleId);
        $role->roleAccess = $role->roleAccess ? $role->roleAccess->toArray() : [];
        $role = $role->toArray();
        unset($role['role_access']);
        return $role;
    }

    /**
     * 设置
     * @param $roleId
     * @return bool
     */
    public static function set($roleId)
    {
        return Cache::tags(self::CACHE_TAG)->put($roleId, self::handleData($roleId));
    }

    /**
     * 获取
     * @param $roleId
     * @return mixed
     */
    public static function get($roleId)
    {
        $instance = new self();
        return Cache::tags(self::CACHE_TAG)->rememberForever($roleId, function() use ($roleId, $instance)  {
            return $instance->handleData($roleId);
        });
    }

    /**
     * 删除缓存
     * @param $roleId
     * @return bool
     */
    public static function del($roleId)
    {
        return Cache::tags(self::CACHE_TAG)->forget($roleId);
    }

    /**
     * 获取角色权限ID列表
     * @param $roleId
     * @return array
     */
    public static function access($roleId)
    {
        $role = self::get($roleId);
        return $role['roleAccess'];
    }

    /**
     * 重置缓存
     */
    public static function reset()
    {
        Cache::tags(self::CACHE_TAG)->flush();
        $roleIds = Role::get('id')->pluck('id')->all();
        foreach ($roleIds as $roleId) {
            self::set($roleId);
        }
    }
}
